<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="pageChange(1)"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="pageChange(1)">查询</el-button>
    </template>
    <template slot="content">
      <callTable
              :headers="tableHeaders"
              :data="tableData"
              :pagingData="pagingData"
              @pageChange="pageChange"
              @pageSizeChange="pageSizeChange"
              @checkHeadersChange="checkHeadersChange"
              v-loading="showLoading"
              ref="callTabel">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="item.label + index"
                    :sortable="item.sortable"
                    :min-width="item.width > 0 ? item.width : ''"
                    :show-overflow-tooltip="true"
                    align="left"
                    v-if="
                item.show &&
                item.prop !== 'oprate' &&
                item.prop !== 'status' && item.prop !== 'count'
              "
            >
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :key="index"
                    align="left"
                    v-if="item.show && item.prop === 'status'"
            >
              <template slot="header">
                <span>状态</span>
                <el-tooltip effect="dark" content="成功的任务会在30天后自动失效，请尽快下载" placement="top">
                  <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <i  class="V7_iconfont V7_iconV7tubiao_dian" :class="
                scope.row.status === 'SUCCEED' ? 'green-color':
                scope.row.status === 'PARTIAL' ? 'orange-color':
                scope.row.status === 'FAILED'?'red-color':
                scope.row.status === 'EXPORTING' || scope.row.status === 'PENDING'?'blue-color':'gray-color'"

                ></i>
                {{ scope.row.status | getStausName }}
              </template>
            </u-table-column>
          <u-table-column
                  :label="item.label"
                  :key="index"
                  align="left"
                  v-if="item.show && item.prop === 'count'">
              <template slot-scope="scope">
                <span v-if="scope.row.status === 'PARTIAL'">{{scope.row.successCount || 0}}/{{scope.row.count || 0}}</span>
                <span v-else>{{scope.row.count || 0}}</span>
              </template>
          </u-table-column>
            <u-table-column
                    :label="item.label"
                    v-if="item.prop === 'oprate' && item.show"
                    :key="item.label + index"
                    align="right"
                    fixed="right"
                    width="80">
              <template slot-scope="scope">
                <!--有下载权限 && (失效的除外)多文件下载 =》 弹窗选择要下载的文件-->
                <span class="oprate-btn" v-if="showDownLoad && scope.row.status!=='INVALID'&&scope.row.downloadUrls && scope.row.downloadUrls.length > 1" @click="handleDownload(scope.row)">下载</span>
                <!--有下载权限 && (失效的除外)单个文件，直接下载-->
                <a class="oprate-btn" v-if="showDownLoad && scope.row.status!=='INVALID'&& scope.row.downloadUrls && scope.row.downloadUrls.length === 1" :href="scope.row.downloadUrls[0].url+'?name='+scope.row.downloadUrls[0].name"  target="_blank"  download>下载</a>
                <!--有删除载权限 &&只要不是进行中的操作 =》!（正在导出 || 排队中 || 导入中） =》 (删除操作)-->
                <span class="oprate-btn red-color" v-if="showDelete && !(scope.row.status === 'EXPORTING' || scope.row.status === 'PENDING' || scope.row.status === 'IMPORTING')"  @click="handleDeleteOrCancle(scope.row, 'delete')">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </callTable>
      <MultiFiledDialog ref="multiFiledDialogRef"></MultiFiledDialog>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Prop, Ref } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import callTable from '@/components/configCommon/table.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import MultiFiledDialog from './MultiFiledDialog.vue'
import { isHasFuncOrMenus, getFormatDateTime, deepClone } from '@/utils/common'
@Component({
  name: 'taskList',
  components: { callTable, continer, QuickSearch, MultiFiledDialog },
  filters: {
    getStausName (status) {
      let statusName = '未知状态'
      switch (status) {
        case 'SUCCEED':
          statusName = '成功'
          break;
        case 'PARTIAL':
          statusName = '部分成功'
          break;
        case 'FAILED':
          statusName = '失败'
          break;
        case 'INVALID':
          statusName = '失效'
          break;
        case 'EXPORTING':
          statusName = '正在导出'
          break;
        case 'IMPORTING':
          statusName = '导入中'
          break;
        case 'PENDING':
          statusName = '排队中'
          break;
      }
      return statusName
    }
  }
})
export default class CallRecord extends Vue {
  [x: string]: any
  @Prop({ default: '' }) private moduleType!: string
  @Prop({ default: null }) private quickSearchPlaceholder!: string
  @Prop({ default: null }) private propsTableHeaders!: any
  @Prop({ default: null }) private taskSource!: any
  @Ref() private multiFiledDialogRef !: MultiFiledDialog
  private $store: any

  private showDownLoad: boolean = false
  private showDelete: boolean = false

  private pagingData: any = { total: 0, limit: 10, page: 1 } // 翻页（总数，每页几条，当前第几页）

  private showLoading = false // table的loading控制

  private exportStateOptions: object[] = [ // 导出的状态搜索下拉
    { name: '成功', _id: 'SUCCEED' },
    { name: '失败', _id: 'FAILED' },
    { name: '失效', _id: 'INVALID' },
    { name: '正在导出', _id: 'EXPORTING' },
    { name: '排队中', _id: 'PENDING' }
  ]

  private importStateOption: object[] = [ // 导入的状态搜索下拉
    { name: '成功', _id: 'SUCCEED' },
    { name: '部分成功', _id: 'PARTIAL' },
    { name: '失败', _id: 'FAILED' },
    { name: '失效', _id: 'INVALID' },
    { name: '导入中', _id: 'IMPORTING' },
    { name: '排队中', _id: 'PENDING' }
  ]

  private quickSearchForm: any = { // 快捷检索数据（时间条件，类型）
    form: {
      quickSearch: '',
      status: [],
      createTime: '',
      type: []
    },
    advSearchOptions: [ // 快捷检索的数据
      { label: '快捷检索', inputType: 'input', placeholder: this.quickSearchPlaceholder || '输入ID或备注', name: 'quickSearch', clearable: true },
      { label: '状态', inputType: 'select', clearable: true, selectData: this.moduleType === 'import' ? this.importStateOption : this.exportStateOptions, name: 'status', multiple: true },
      { label: '创建时间', inputType: 'dateTimeRange', clearable: true, name: 'createTime' },
      { label: '任务来源', inputType: 'select', clearable: true, selectData: this.taskSource, name: 'type', multiple: true }
    ]
  }

  private pickerOptions: any = {
    shortcuts: [{
      text: '最近一周',
      onClick (picker: any) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }, {
      text: '最近一个月',
      onClick (picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }, {
      text: '最近三个月',
      onClick (picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 89)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }]
  }

  private tableHeaders = [ // 自定义表头
    {
      label: '任务ID',
      prop: 'taskId',
      width: 100
    },
    {
      label: '状态',
      prop: 'status'
    },
    {
      label: '总数',
      prop: 'count'
    },
    {
      label: '任务来源',
      prop: 'typeName'
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 100
    },
    {
      label: '创建人',
      prop: 'createName'
    },
    {
      label: '备注',
      prop: 'comment'
    },
    {
      label: '失败原因',
      prop: 'failReason'
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private checkHeaders = []

  private tableData = [] // list 数据

  private checkHeadersChange (checkList, isInit) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private handleDownload (row: any) { // 下载多文件
    const downloadList = row.downloadUrls || []
    downloadList.forEach((item: any) => {
      if (item.size && typeof item.size === 'number') {
        item.size = `${Math.ceil(item.size / 1024 / 1024)}M` // 从B换算成M
        if (item.size > 1024) {
          item.size = `${Math.ceil(item.size / 1024)}G` // 从M换算成G
        }
      }
    })
    this.multiFiledDialogRef.setDialogData(downloadList)
  }

  private handleDeleteOrCancle (row: any, type: string) { // 删除或者取消任务
    this.$confirm(`确定要${type === 'delete' ? '删除' : '取消'}此任务吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionData = { taskId: row.taskId }
      const data = { url: '/base/action/transmission/export/task/cancel', method: 'POST', data: actionData }
      if (type === 'delete') {
        data.url = this.moduleType === 'import' ? '/base/action/transmission/import/task/delete' : '/base/action/transmission/export/task/delete'
      }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success) {
          this.getTaskList()
        }
      })
    }).catch(() => {
      console.log('取消')
    })
  }

  private handelList (resData) { // 请求回来之后，处理table的数据
    resData.forEach((item: any) => {
      const agentObj = deepClone(this.$store.state.common.publicCache.userListObj)[item.createUser]
      item.createName = agentObj ? agentObj.name : '--'
      const typeArr: any = this.taskSource.filter((item2: any) => item2._id === item.type)
      item.typeName = typeArr[0] ? typeArr[0].name : ''
    })
    return resData
  }

  private getTaskList () { // 获取任务列表
    this.showLoading = true
    const time = this.quickSearchForm.form.createTime || []
    if (time && time.length > 0) {
      this.quickSearchForm.form.createTime = [getFormatDateTime(time[0], ''), getFormatDateTime(time[1], '')]
    } else {
      this.quickSearchForm.form.createTime = []
    }
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page, type: 'cdr' }, this.quickSearchForm.form)
    const url = this.moduleType === 'import' ? '/base/action/transmission/import/task/query' : '/base/action/transmission/export/task/query'
    const data = { url, method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success) {
        const resData = this.handelList(res.data.list || [])
        this.tableData = resData || []
        this.pagingData.total = res.data.count || 0
        if (resData.length === 0) {
          const page = Math.ceil(res.data.count / this.pagingData.limit)
          if (!res.data.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.getTaskList()
            return false
          }
        }
      }
      this.showLoading = false
    }).catch(() => {
      this.showLoading = false
      this.tableData = []
      this.pagingData.total = 0
    })
  }

  private pageChange (page) { // 翻页change
    this.pagingData.page = page
    this.getTaskList()
  }

  private pageSizeChange (size) { // 修改每页/条
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.getTaskList()
  }

  private handleLimit () { // 权限控制
    let arr: any[] = []
    if (this.moduleType === 'import') {
      arr = ['tx_import_task_download', 'tx_import_task_delete'] // 下载，删除 (通话记录)
    } else if (this.moduleType === 'export') {
      arr = ['tx_export_task_download', 'tx_export_task_delete'] // 下载，删除 (通话记录)
    }
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, false)) {
        if (item.indexOf('_download') > -1) { // 下载
          this.showDownLoad = true
        }
        if (item.indexOf('_delete') > -1) { // 删除
          this.showDelete = true
        }
      }
    })
  }

  private activated () {
    // 组件被重新激活,再查询一次列表
    const taskId = this.$route.query.previewTaskId || ''
    this.quickSearchForm.form.quickSearch = taskId
    this.quickSearchForm.form.type = this.$route.query.taskModule ? [this.$route.query.taskModule] : []
    this.getTaskList()
  }

  private beforeMount () {
    this.handleLimit() // 权限处理
  }
}
</script>

<style lang="stylus" scoped>
.oprate-btn
  color $c-main
  margin-right 10px
  cursor pointer
.oprate-btn:hover
  opacity 0.8
.green-color
  color $c-green
.orange-color
  color $c-warn
.red-color
  color $c-danger
.gray-color
  color $icon-gray
.blue-color
  color $c-main
.tip-span
  color $icon-gray
  cursor pointer
  margin-left 4px
  font-size 14px
</style>
